﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace dataSendModel.Util
{
    public static class CodeConvert
    {
        static string controlCode = string.Empty; //控制码
        static string reContent = string.Empty;  //内容
        static string crc = string.Empty; //crc校验
        static StringBuilder sb1 = null;
        public static string getReaderMsg(string value, string modiType, string readerAdress)
        {
            //时间间隔5AA5 234565 01 00030101 000001 AFAC
            sb1 = new StringBuilder("5AA5" + readerAdress);
            value = (int.Parse(value)).ToString("X2"); //设置的值
            switch (modiType)
            {
                case "天线1灵敏度":
                    controlCode = "09";
                    reContent = "0001" + value;
                    break;
                case "天线2灵敏度":
                    controlCode = "09";
                    reContent = "0002" + value;
                    break;
                case "上传时间间隔":
                    controlCode = "01";
                    reContent = "0000" + value;
                    break;
            }
            sb1.Append(controlCode + "00030101");
            sb1.Append(reContent);
            byte[] cc = stringToHex(sb1.ToString());
            crc = CRC_CCITTConvert.getCRC_CCITT(cc, cc.Length);
            sb1.Append(crc);
            return sb1.ToString();
        }

        static string leng = string.Empty;
        static int len = 0; //长度
        static string ccrc = string.Empty;
        static string ccontent = string.Empty;
        static string qccrc = string.Empty;
        //检查reader数据是否正确
        public static bool checkReaderCode(string str)
        {
            try
            {
                if (!str.Equals("") && str.Length >= 16) //判断是否有16个位数
                {
                    leng = str.Substring(12, 4);  
                    len = Convert.ToInt32(leng, 16) << 1;  //数据内容长度
                    ccontent = str.Substring(20, str.Length - 24); //截到数据内容
                    byte[] cc = stringToHex(str.Substring(0,str.Length-4));  //从头截取到验证码前
                    qccrc = CRC_CCITTConvert.getCRC_CCITT(cc, cc.Length);  //求到验证码
                    ccrc = str.Substring(str.Length - 4); //原来验证码
                    if (ccontent.Length == len && qccrc.Equals(ccrc)) //判断内容长度是否符合
                    {
                        return true;
                    }
                    return false;
                }
            }
            catch (Exception)
            {
                return false;
            }
            return false;
        }

        static string gpsIdZ = string.Empty;
        //得到gps完整注册信息
        public static string getGpsRegist(string gpsId)
        {
            gpsId = "01C2089069" + gpsId + "FF0D0A";
            gpsIdZ = Get_CheckXor(gpsId);
            gpsId = "1002"+gpsId + gpsIdZ + "1003";
            return gpsId;
        }

        //得到GPS身份码
        public static string getGpsAdress(string str)
        {
            str = str.Replace(" ", "");
            return str.Substring(14, 6);
        }

        //检查是否有65指令的数据
        public static bool checkGpsCode(string str)
        {
            str = str.Replace(" ", "");
            str = str.Substring(2, 2);
            if (str.Equals("65"))
            {
                return true;
            }
            return false;
        }

        //得到基站地址码
        public static string getReaderAdress(string str)
        {
            str = str.Replace(" ", "");
            if (str.Contains("5AA5"))
            {
                return str.Substring(4, 6);
            }
            return string.Empty;
        }

        static StringBuilder sb = null;
        static int conLen = 0; //内容字节长度
        static string xor = string.Empty; //得到异或校验

        //取得内容合并成带帧头帧尾的完整数据
        public static string sendGpsMsg(string hexString)
        {
            sb = new StringBuilder("1002");
            hexString = hexString.Replace(" ", "");
            hexString = hexString.Replace("1010", "10");
            conLen = hexString.Length / 2;
            hexString = "00C1" + conLen.ToString("X2") + hexString; //序列号到内容
            xor = Get_CheckXor(hexString); 
            sb.Append(hexString);
            sb.Append(xor);
            sb.Append("1003");
            return sb.ToString();
        }

        static string xuLieXinLing = string.Empty;//序列和信令码
        static string lengStr = string.Empty;//取出内容长度
        static string xorStr = string.Empty;//取得校验码
        static string content = string.Empty;//取得的内容
        //分析数据是否符合要求并返回合格的内容部分
        public static byte[] getGpsMsg(string hexString)
        {
            hexString = hexString.Replace(" ", "");
            hexString = hexString.Replace("1010", "10");
            xuLieXinLing = hexString.Substring(4, 4); 
            lengStr = hexString.Substring(8, 2);  
            xorStr = hexString.Substring(hexString.Length - 6, 2); 
            hexString = hexString.Substring(10);
            content = hexString.Substring(0, hexString.Length - 6);
            byte[] returnByte = null;
            if (((content.Length / 2).ToString("X2")).Equals(lengStr) && xorStr.Equals(Get_CheckXor(xuLieXinLing + lengStr + content)))
            {
                returnByte = stringToHex(content); //返回的字节数组
            }
            return returnByte;
        }

        //异或校验
        public static string Get_CheckXor(string str)
        {
            byte[] temp = stringToHex(str);
            byte A = 0;
            for (int i = 0; i < temp.Length; i++)
            {
                A ^= temp[i];
            }
            return A.ToString("X2");
        }


        static byte[] returnBytes = null;
        static string temp = string.Empty;
        /// <summary>
        /// 字符串转16进制字节数组
        /// </summary>
        /// <param name="hexString"></param>
        /// <returns></returns>
        public static byte[] stringToHex(string hexString)
        {
            hexString = hexString.Replace(" ", "");
            if ((hexString.Length % 2) != 0)
            {
                hexString += " ";
            }
            returnBytes = new byte[hexString.Length / 2];
            for (int i = 0; i < returnBytes.Length; i++)
            {
                temp = hexString.Substring(i * 2, 2);
                returnBytes[i] = Convert.ToByte(temp, 16);
            }
            return returnBytes;

        }


        /// <summary>
        /// 字节数组转16进制字符串
        /// </summary>
        /// <param name="bytes"></param>
        /// <returns></returns>
        public static string byteToHexStr(byte[] bytes)
        {
            string returnStr = string.Empty;
            if (bytes != null)
            {
                for (int i = 0; i < bytes.Length; i++)
                {
                    returnStr += bytes[i].ToString("X2");
                }
            }
            return returnStr;
        }



        /// <summary>
        /// 从汉字转换到16进制
        /// </summary>
        /// <param name="s"></param>
        /// <param name="charset">编码,如"utf-8","gb2312"</param>
        /// <param name="fenge">是否每字符用逗号分隔</param>
        /// <returns></returns>
        public static string ToHex(string s, string charset, bool fenge)
        {
            if ((s.Length % 2) != 0)
            {
                s += " ";//空格
                //throw new ArgumentException("s is not valid chinese string!");
            }
            System.Text.Encoding chs = System.Text.Encoding.GetEncoding(charset);
            byte[] bytes = chs.GetBytes(s);
            string str = "";
            for (int i = 0; i < bytes.Length; i++)
            {
                str += string.Format("{0:X}", bytes[i]);
                if (fenge && (i != bytes.Length - 1))
                {
                    str += string.Format("{0}", ",");
                }
            }
            return str.ToLower();
        }



        ///<summary>
        /// 从16进制转换成汉字
        /// </summary>
        /// <param name="hex"></param>
        /// <param name="charset">编码,如"utf-8","gb2312"</param>
        /// <returns></returns>
        public static string UnHex(string hex, string charset)
        {
            if (hex == null)
            {
                throw new ArgumentNullException("hex");
            }
            hex = hex.Replace(",", "");
            hex = hex.Replace("\n", "");
            hex = hex.Replace("\\", "");
            hex = hex.Replace(" ", "");
            if (hex.Length % 2 != 0)
            {
                hex += "20";//空格
            }
            // 需要将 hex 转换成 byte 数组。 
            byte[] bytes = new byte[hex.Length / 2];

            for (int i = 0; i < bytes.Length; i++)
            {
                try
                {
                    // 每两个字符是一个 byte。 
                    bytes[i] = byte.Parse(hex.Substring(i * 2, 2),
                    System.Globalization.NumberStyles.HexNumber);
                }
                catch
                {
                    // Rethrow an exception with custom message. 
                    throw new ArgumentException("hex is not a valid hex number!", "hex");
                }
            }
            System.Text.Encoding chs = System.Text.Encoding.GetEncoding(charset);
            return chs.GetString(bytes);
        }

        /// <summary>
        /// 数组转换成long
        /// </summary>
        /// <param name="arr"></param>
        /// <param name="Offset"></param>
        /// <param name="VarLength"></param>
        /// <returns></returns>
        public static long convertBytesToLong(byte[] arr,int VarLength)
        {
            long num = 0L;
            int Offset = 0;
            try
            {
                if (VarLength == 4)
                {
                    num += Convert.ToInt64(arr[Offset + 3]);
                    num += (long)(Convert.ToInt64(arr[Offset + 2]) * Math.Pow(2.0, 8.0));
                    num += (long)(Convert.ToInt64(arr[Offset + 1]) * Math.Pow(2.0, 16.0));
                    return (num + ((long)(Convert.ToInt64(arr[Offset]) * Math.Pow(2.0, 24.0))));
                }
                if (VarLength == 2)
                {
                    num += Convert.ToInt64(arr[Offset + 1]);
                    num += Convert.ToInt64((double)(arr[Offset] * Math.Pow(2.0, 8.0)));
                }
            }
            catch (Exception exception)
            {
                throw new Exception("Error in Converting Bytes to Long()", exception);
            }
            return num;
        }

    }
}
